﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;

namespace YYTmEditer.MtObject
{
    public class NameMap
    {
        public static NameMap BlessName;
        public static NameMap CardName;
        public static NameMap ShopName;
        public readonly Dictionary<string, string> names;

        NameMap() {
            names = new Dictionary<string, string>();
        }

        public static void loadConfig() {
            
            BlessName = newInst("bless");
            CardName = newInst("card");
            ShopName = newInst("shop");
        }

        private static NameMap newInst(string resName) {
            var res = Properties.Resources.ResourceManager.GetString(resName);
            NameMap nmap = JsonConvert.DeserializeObject<NameMap>(res);
            
            nmap.readExtFile(resName);
            return nmap;
        }
        private string fileName = "bless.json";

        private void readExtFile(string resName)
        {
            this.fileName = resName + ".json";
            if (File.Exists(fileName))
            {
                string text = File.ReadAllText(fileName);
                this.Merge(text);
            }
        }

        private void Merge(string text) {
            NameMap nm = JsonConvert.DeserializeObject<NameMap>(text);
            if (nm!=null) {
                for (var e = nm.names.GetEnumerator(); e.MoveNext();) {
                    var kp = e.Current;
                    names[kp.Key] = kp.Value;
                }
            }
        }

        public bool Contains(string name) {
            return names.ContainsKey(name);
        }

        public string GetValue(string name)
        {
            return names[name];
        }

        public void SetValue(string name, string value) {
            names[name] = value;
            string data  = JsonConvert.SerializeObject(this);
            File.WriteAllText(fileName, data);
        }

        
    }
}
